package org.dromara.iot.handler;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.mqtt.handler.MqttMessageHandler;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.iot.domain.mq.ElevatorStatus;
import org.dromara.iot.domain.vo.IotElevatorVo;
import org.dromara.iot.service.IIotElevatorService;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;

@Slf4j
@RequiredArgsConstructor
@Service
public class StatusMessageHandler implements MqttMessageHandler {
    private final IIotElevatorService elevatorService;

    @Override
    public void handle(String code, MqttMessage message) {
        IotElevatorVo iotElevator = elevatorService.selectByRegisteredCode(code);
        if (iotElevator == null) {
            log.error("接收到状态消息，但电梯不存在:{}", code);
            return;
        }
        log.info("接收到状态消息:{}：{}", code, message.toString());
        ElevatorStatus elevatorStatus = JSONUtil.toBean(new String(message.getPayload()), ElevatorStatus.class);
        log.info("解析后的状态消息:{}", elevatorStatus);
        RedisUtils.setCacheObject(GlobalConstants.GLOBAL_REDIS_KEY + "elevatorStatus:" + iotElevator.getElevatorId(), elevatorStatus);
    }
}
